package server

import (
	"context"
	"fmt"
	"gitee.com/tietang/terrace-go/v2/lib/rpc"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/mo/entity"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/mo/service"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/seri"
	log "github.com/sirupsen/logrus"
)

var _ service.RpcService = new(RpcHandler)

type RpcHandler struct {
}

func (m RpcHandler) Write(ctx context.Context, mo *entity.MoEntity) (res *entity.ResEntity, err error) {
	res = entity.NewResEntity()
	res.Code = "200"
	res.Message = "成功"
	//log.Debug("数据：", mo.Type, " = ", string(mo.Data))
	res, err = rpc.Dispatch(mo)
	return

}

func (m RpcHandler) Ping(ctx context.Context) (res string, _err error) {
	return "pong", _err
}

func (m RpcHandler) Login(ctx context.Context, loginEntity *entity.LoginEntity) (res *entity.ResEntity, _err error) {
	res = entity.NewResEntity()
	res.Code = "200"
	res.Message = "成功"
	if loginEntity.GetSerialType() == seri.SERIAL_TYPE_JSON_CODE {
		res.SerialType = seri.SERIAL_TYPE_JSON_CODE
		return
	}
	if loginEntity.GetSerialType() == seri.SERIAL_TYPE_BSON_CODE {
		res.SerialType = seri.SERIAL_TYPE_BSON_CODE
		return
	}

	for _, serialType := range loginEntity.SupportedSerialTypes {
		if serialType == seri.SERIAL_TYPE_JSON_CODE {
			res.SerialType = seri.SERIAL_TYPE_JSON_CODE
			return
		}
		if serialType == seri.SERIAL_TYPE_BSON_CODE {
			res.SerialType = seri.SERIAL_TYPE_BSON_CODE
			return
		}
	}
	res.Code = "500"
	res.Message = fmt.Sprintf("无可用支持的序列化类型：%v %v", loginEntity.SerialType, loginEntity.SupportedSerialTypes)
	log.Info(res.Message)
	return

}
